package com.jzo2o.foundations.listener;

import cn.hutool.json.JSONUtil;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.ServeSearch;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: liZhiJun
 * @CreateTime: 2025-09-24
 * @Description: ES监听器
 */
@Component
@Slf4j
public class ESListener {

    @Autowired
    private ServeMapper serveMapper;
    @Autowired
    private RestHighLevelClient client;

    /**
     * 服务上架监听
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "serve.onSale.queue", durable = "true"),
            exchange = @Exchange(name = "serve.exchange"),
            key = {"serve.onSale"}
    ))
    public void serveAdd(String idStr) {
        //1.查询服务详情
        log.info("服务上架监听{}", idStr);
        Long id = Long.valueOf(idStr);
        ArrayList<Long> list = new ArrayList<>();
        list.add(id);
        //2.生成服务详情
        List<ServeSearch> serves = serveMapper.SearchBatchIds(list);
        if (CollectionUtils.isEmpty(serves)) {
            log.info("没有服务详情");
            return;
        }
        //3.保存服务详情
        //3.1 新建请求
        BulkRequest bulkRequest = new BulkRequest("serve");
        serves.forEach(serve -> {
            IndexRequest request = new IndexRequest();
            request.id(serve.getId().toString())
                    .source(JSONUtil.toJsonStr(serve), XContentType.JSON);
            bulkRequest.add(request);
        });
        try {
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
            log.info("成功插入{}条数据", serves.size());
        } catch (Exception e) {
            log.error("插入失败", e);
        }

    }

    /**
     * 服务删除监听
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "serve.offSale.queue"),
            exchange = @Exchange(name = "serve.exchange"),
            key = {"serve.offSale"}
    ))
    public void serveDelete(String serveId) {
        //1.删除服务详情
        log.info("服务下架监听{}", serveId);
        long id = Long.parseLong(serveId);
        //2.创建  请求
        DeleteRequest request = new DeleteRequest("serve", serveId);
        try {
            client.delete(request, RequestOptions.DEFAULT);
            log.info("成功删除服务{}", serveId);
        } catch (Exception e) {
            log.error("删除服务失败", e);
        }

    }

    /**
     * 服务修改监听
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "serve.updatePrice.queue"),
            exchange = @Exchange(name = "serve.exchange"),
            key = {"serve.updatePrice", "serve.update"}
    ))
    public void serveUpdate(String serveId) {
        //1.查询服务详情
        log.info("服务价格修改监听{}", serveId);
        Long id = Long.valueOf(serveId);
        ArrayList<Long> list = new ArrayList<>();
        list.add(id);
        //2.生成服务详情
        List<ServeSearch> serves = serveMapper.SearchBatchIds(list);
        if (CollectionUtils.isEmpty(serves)) {
            log.info("没有服务详情");
            return;
        }
        //2.生成修改请求
        UpdateRequest updateRequest = new UpdateRequest("serve", serveId);
        updateRequest.doc(JSONUtil.toJsonStr(serves.get(0)), XContentType.JSON);
        //3.修改es
        try {
            client.update(updateRequest, RequestOptions.DEFAULT);
            log.info("成功修改服务{}", serveId);
        } catch (IOException e) {
           log.error("修改服务详情失败", e);
        }
    }

}
